package com.zhouxiaoge.jenkins.core.service.impl;

import com.offbytwo.jenkins.JenkinsServer;
import com.zhouxiaoge.jenkins.core.service.JenkinsManageWorkFlowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author 周明阳
 * @date 2019/7/18 15:59
 */

@Service
@Slf4j
public class JenkinsManageWorkFlowServiceImpl implements JenkinsManageWorkFlowService {

    private final JenkinsServer jenkinsServer;

    public JenkinsManageWorkFlowServiceImpl(JenkinsServer jenkinsServer) {
        this.jenkinsServer = jenkinsServer;
    }

    @Override
    public void createWorkFlow(String workFlowName) {
        String workFlowXml = "<flow-definition plugin=\"workflow-job@2.33\">\n" +
                "<description>流水线pipelineX测试</description>\n" +
                "<keepDependencies>false</keepDependencies>\n" +
                "<properties/>\n" +
                "<definition class=\"org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition\" plugin=\"workflow-cps@2.72\">\n" +
                "<script>node { echo 'Hello World' }</script>\n" +
                "<sandbox>true</sandbox>\n" +
                "</definition>\n" +
                "<triggers/>\n" +
                "<disabled>false</disabled>\n" +
                "</flow-definition>";
        try {
            jenkinsServer.createJob(workFlowName, workFlowXml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateWorkFlow(String workFlowName, String pipelineXml) {
        try {
            String description = jenkinsServer.getJob(workFlowName).getDescription();
            String workFlowXml = "<flow-definition plugin=\"workflow-job@2.33\">\n" +
                    "  <description>" + description + "</description>\n" +
                    "  <keepDependencies>false</keepDependencies>\n" +
                    "  <properties/>\n" +
                    "  <definition class=\"org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition\" plugin=\"workflow-cps@2.72\">\n" +
                    "    <script>\n" + pipelineXml + "\n</script>\n" +
                    "    <sandbox>true</sandbox>\n" +
                    "  </definition>\n" +
                    "  <triggers/>\n" +
                    "  <disabled>false</disabled>\n" +
                    "</flow-definition>";
            jenkinsServer.updateJob(workFlowName, workFlowXml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
